package com.halloon.android.util;

import java.util.concurrent.ExecutionException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ClipData;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.halloon.android.R;
import com.halloon.android.data.ContentManager;
import com.halloon.android.data.SettingsManager;
import com.halloon.android.image.ImageLoader;
import com.halloon.android.task.ImageLoadTask;
import com.halloon.android.ui.fragment.CommentFragment;
import com.halloon.android.ui.fragment.TabMainPageFragment.MainPageFragmentCallback;

public class PopupWindowManager{
	private Context context;
	
	private PopupWindow popupWindow;
	private ViewGroup container;
	
	//forPicturePopupOnly
	private TextView loading;
	private ImageView picturePopup;
	private ImageLoadTask picturePopupTask;
	
	public static int OTHER_TWEET_FUNCTION = 0;
	public static int MY_TWEET_FUNCTION = 1;
	
	
	public PopupWindowManager(Context context){
		this.context = context;
	}
	
	public void setupPicturePopup(final String addr, final String size){
		container = (ViewGroup) ((Activity) context).getLayoutInflater().inflate(R.layout.popup_picture, null);
		OnClickListener buttonClickListener = new OnClickListener(){
			@Override
			public void onClick(View v){
				switch(v.getId()){
				case R.id.popup_back_button:
					popupWindowDismiss();
					break;
				case R.id.save_button:
					try {
						if(ImageLoader.imageSave(picturePopupTask.get())){
							Toast.makeText(context, context.getString(R.string.saved), Toast.LENGTH_LONG).show();
						}else{
							Toast.makeText(context, context.getString(R.string.could_not_save_check_sdcard), Toast.LENGTH_LONG).show();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					} catch (ExecutionException e) {
						e.printStackTrace();
					}
					break;
				}
			}
		};
		container.findViewById(R.id.popup_back_button).setOnClickListener(buttonClickListener);
		container.findViewById(R.id.save_button).setOnClickListener(buttonClickListener);
		popupWindow = new PopupWindow(container, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(-00000));
		popupWindow.setAnimationStyle(R.style.PopupWindowFade);
		popupWindow.showAtLocation(((Activity) context).findViewById(R.id.title_layout), Gravity.NO_GRAVITY, 0, SettingsManager.getInstance(context).getSystemBarHeight());
		
		loading = (TextView) container.findViewById(R.id.loading);
		picturePopup = (ImageView) container.findViewById(R.id.popup_image);
		picturePopupTask = new ImageLoadTask(context, picturePopup, loading);
		
		if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			picturePopupTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, addr + size);
		}else{
			picturePopupTask.execute(addr + size);
		}
	}
	
	public void setupCommentBar(int y){
		container = (ViewGroup) ((Activity) context).getLayoutInflater().inflate(R.layout.comment_bar, null);
		popupWindow = new PopupWindow(container, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(-00000));
		popupWindow.setAnimationStyle(R.style.CommentBarZoom);
		popupWindow.showAtLocation(((Activity) context).findViewById(R.id.title_layout), Gravity.NO_GRAVITY, 0, y);
	}
	
	public void setupCommentFunctionPopup(final String tweetId, final boolean isMe, final String content, final int type, final int positionInList){
		container = (ViewGroup) ((Activity) context).getLayoutInflater().inflate(R.layout.comment_popup, null);
		
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1);
		
		if(type == OTHER_TWEET_FUNCTION){
			adapter.add(context.getString(R.string.comment));
			adapter.add(context.getString(R.string.retweet));
			adapter.add(context.getString(R.string.copy));
			if(isMe) adapter.add(context.getString(R.string.delete));
		}else{
			adapter.add(context.getString(R.string.comment));
			adapter.add(context.getString(R.string.retweet));
			adapter.add(context.getString(R.string.copy));
			adapter.add(context.getString(R.string.delete));
		}
		System.out.println(isMe);
		
		ListView list = (ListView) container.findViewById(R.id.functional);
		list.setAdapter(adapter);
		list.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				// TODO Auto-generated method stub
				Bundle bundle = new Bundle();
				
				switch(position){
				case 0:
					bundle.putInt("type", CommentFragment.COMMENT);
					bundle.putString("id", tweetId);
					((MainPageFragmentCallback) context).setupCommentFragment(bundle);
					popupWindow.dismiss();
					break;
				case 1:
					bundle.putInt("type", CommentFragment.RETWEET);
					bundle.putString("id", tweetId);
					((MainPageFragmentCallback) context).setupCommentFragment(bundle);
					popupWindow.dismiss();
					break;
				case 2:
					if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
			        	android.content.ClipboardManager cbManagerForApi11 = (android.content.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
			        	ClipData clipData = ClipData.newPlainText("tweet_content", content);
			        	cbManagerForApi11.setPrimaryClip(clipData);
			        }else{
			        	android.text.ClipboardManager cbManager = (android.text.ClipboardManager) context.getSystemService(Activity.CLIPBOARD_SERVICE);
					    cbManager.setText(content);//should use setPrimaryClip() after API Level 11;
			        }
					
					Toast.makeText(context, context.getString(R.string.already_copy), Toast.LENGTH_LONG).show();
					popupWindow.dismiss();
					break;
				case 3:
					AlertDialog.Builder builder = new AlertDialog.Builder(context);
					builder.setTitle(context.getString(R.string.delete_tweet))
					       .setIcon(R.drawable.ic_launcher)
					       .setCancelable(true)
					       .setMessage(context.getString(R.string.confirm_delete))
					       .setPositiveButton(context.getString(R.string.confirm), new DialogInterface.OnClickListener(){
					    	   @Override
					    	   public void onClick(DialogInterface dialog, int which){
					    		   new Thread(){
					    			   @Override
					    			   public void run(){
					    				   ContentManager.getInstance(context).delTweet(tweetId);
					    			   }
					    		   }.start();
					    		   Intent intent = new Intent();
					    		   Bundle bundle = new Bundle();
					    		   bundle.putInt("position", positionInList);
					    		   intent.setAction(Constants.DEL_CONFIRM);
					    		   intent.putExtras(bundle);
					    		   context.sendBroadcast(intent);
					    		   popupWindow.dismiss();
					    	   }
					       })
					       .setNegativeButton(context.getString(R.string.cancel), new DialogInterface.OnClickListener(){
					    	   @Override
					    	   public void onClick(DialogInterface dialog, int which){
					    		   
					    	   }
					       });
					AlertDialog dlg = builder.create();
					dlg.show();
					break;
				}
			}
			
		});
		popupWindow = new PopupWindow(container, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(-00000));
		popupWindow.setAnimationStyle(R.style.PopupWindowYAxisSlide);
		popupWindow.showAtLocation(((Activity) context).findViewById(R.id.title_layout), Gravity.NO_GRAVITY, 0, SettingsManager.getInstance(context).getSystemBarHeight());
	}
	
	public void setupTitleListPopup(int parentViewRes, BaseAdapter adapter){
		container = (ViewGroup) ((Activity) context).getLayoutInflater().inflate(R.layout.title_list, null);
		ListView list = (ListView) container.findViewById(R.id.list);
		list.setAdapter(adapter);
		popupWindow = new PopupWindow(container, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
		popupWindow.setFocusable(true);
		popupWindow.setBackgroundDrawable(new ColorDrawable(-00000));
		popupWindow.setAnimationStyle(R.style.PopupWindowSlideFade);
		popupWindow.showAtLocation(((Activity) context).findViewById(parentViewRes), Gravity.CENTER|Gravity.TOP, 0, ((Activity) context).findViewById(parentViewRes).getBottom() + SettingsManager.getInstance(context).getSystemBarHeight());
	}
	
	public void popupWindowDismiss(){
		if(picturePopupTask.getStatus() == AsyncTask.Status.RUNNING) picturePopupTask.cancel(true);
		popupWindow.dismiss();
	}

	public boolean isShowing(){
		return popupWindow.isShowing();
	}
}
